package com.wry.wry_test.utils;

import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.csv.CsvFormat;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;

/**
 * @Author: wangrongyi
 * @Date: 2025/1/22 15:56
 * @Description:
 */
@Slf4j
public class CsvUtil {
    /**
     * 读取crv文件并转换成List
     *
     * @param separator crv文件分隔符
     * @param file      待读取文件
     * @return crv对象list
     */
    public static <T> List<T> read(String separator, File file, Class<T> clazz) {
        List<T> result = Collections.emptyList();
        try {
            BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
            //设置分隔符
            CsvFormat csvFormat = new CsvFormat();
            csvFormat.setDelimiter(separator);

            CsvParserSettings parserSettings = new CsvParserSettings();
            parserSettings.setProcessor(rowProcessor);
            parserSettings.setFormat(csvFormat);

            CsvParser parser = new CsvParser(parserSettings);
            InputStream in = Files.newInputStream(file.toPath());
            parser.parse(in);
            //逐行读取
            result = rowProcessor.getBeans();
        } catch (Exception e) {
            log.error("Import csv file failed. message: ", e);
        }
        return result;
    }

}
